<template>
  <CustomNavBar title="绑定车辆"/>
  <view class="page flex-col">
    <view class="box_1 flex-col">
      <view class="group_3 flex-col">
        <text class="text_3">车辆信息</text>
        <view v-if="firstVehicle" class="box_2 flex-col" :class="{ 'active-card': firstVehicle.isDef }">
          <view class="box_3 flex-row justify-between">
            <text class="text_4">{{ firstVehicle.plate }}</text>
            <view v-if="firstVehicle.attestation === 1" class="auth-btn flex-col" @click="goAuth(firstVehicle)">
              <text class="btn-text">去认证</text>
            </view>
            <view v-else class="auth-btn-done flex-col">
              <text class="btn-text-done">已认证</text>
            </view>
          </view>
          <view class="box_4 flex-row justify-between">
            <view class="image-text_1 flex-row justify-between">
              <radio :checked="firstVehicle.isDef" color="#1CCCB4" @click="setDefault(firstVehicle.carId)"/>
              <text class="text-group">设为默认</text>
            </view>
            <text class="divider">I</text>
            <text class="unbind-text" @click="unbindCar(firstVehicle.id)">解绑</text>
          </view>
        </view>
      </view>
      <view v-for="(item, index) in otherVehicles" :key="item.id" class="group_4 flex-col" :class="{ 'active-card': item.isDef, 'first-list-card': index === 0 }">
        <view class="box_5 flex-row justify-between">
          <text class="text_4">{{ item.plate }}</text>
          <view v-if="item.attestation === 1" class="auth-btn flex-col" @click="goAuth(item)">
            <text class="btn-text">去认证</text>
          </view>
          <view v-else class="auth-btn-done flex-col">
            <text class="btn-text-done">已认证</text>
          </view>
        </view>
        <view class="box_6 flex-row justify-between">
          <view class="image-text_1 flex-row justify-between">
            <radio :checked="item.isDef" color="#1CCCB4" @click="setDefault(item.carId)"/>
            <text class="text-group">设为默认</text>
          </view>
          <text class="divider">I</text>
          <text class="unbind-text" @click="unbindCar(item.id)">解绑</text>
        </view>
      </view>
    </view>
    <view class="footer">
      <button class="add-vehicle-btn flex-col" @click="addVehicleBind">
        <text class="add-text">添加车辆</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import CustomNavBar from '@/components/CustomNavBar.vue';
import { onLoad as onPageLoad } from '@dcloudio/uni-app';
import MyApi from '@/api/my/my';

// 车辆列表
const vehicles = ref([]);

// 计算属性：首个车辆与其余车辆
const firstVehicle = computed(() => vehicles.value[0] || null);
const otherVehicles = computed(() => vehicles.value.slice(1));

// 保存当前默认车辆的用户ID与车辆ID
const selectedMemberId = ref(vehicles.value.find(v => v.isDef)?.memberId || null);
const selectedCarId = ref(vehicles.value.find(v => v.isDef)?.carId || null);

onPageLoad(async () => {
  uni.showLoading({ title: '加载中' });
  const res = await MyApi.getBoundVehicles();
  vehicles.value = res;
  // 标准化列表，确保有 id、plate、attestation、isDef、memberId、carId
  // vehicles.value = (Array.isArray(res?.data) ? res.data : Array.isArray(res) ? res : []).map(item => ({
  //   id: item.id ?? item.rltId ?? item.carRltId ?? item.carId, // 兼容不同返回字段
  //   plate: item.plate ?? item.carNumber ?? item.licensePlate ?? '',
  //   attestation: item.attestation ?? item.certStatus ?? 0,
  //   isDef: item.isDef ?? item.defaultFlag ?? false,
  //   memberId: item.memberId ?? item.userId ?? null,
  //   carId: item.carId ?? item.vehicleId ?? null,
  // }));
  uni.hideLoading();
  // 初始化默认车辆
  const def = vehicles.value.find(v => v.isDef);
  selectedMemberId.value = def?.memberId || null;
  selectedCarId.value = def?.carId || null;
});
// 方法
const setDefault = async (carId) => {
  const target = vehicles.value.find(v => v.carId === carId);
  if (!target || target.id == null) {
    uni.showToast({ title: '未找到车辆ID', icon: 'none' });
    return;
  }
  try {
    await MyApi.updateVehicle({ id: target.id, isDef: true });
    vehicles.value = vehicles.value.map(v => ({ ...v, isDef: v.carId === carId }));
    const def = vehicles.value.find(v => v.isDef);
    selectedMemberId.value = def?.memberId || null;
    selectedCarId.value = def?.carId || null;
    uni.showToast({ title: '已设为默认车辆', icon: 'none' });
  } catch (e) {
    console.error('设置默认失败:', e);
    uni.showToast({ title: '设置默认失败', icon: 'none' });
  }
};

const unbindCar = async (relationId) => {
  if (relationId == null) {
    uni.showToast({ title: '缺少ID', icon: 'none' });
    return;
  }
  // 先弹窗确认是否解绑
  uni.showModal({
    title: '提示',
    content: '确定要解绑该车辆吗？解绑后车辆将被删除',
    success: async (res) => {
      if (res.confirm) {
        try {
          await MyApi.deleteVehicle(relationId);
          vehicles.value = vehicles.value.filter(v => v.id !== relationId);
          const def = vehicles.value.find(v => v.isDef);
          selectedMemberId.value = def?.memberId || null;
          selectedCarId.value = def?.carId || null;
          uni.showToast({ title: '已解绑', icon: 'none' });
        } catch (e) {
          uni.showToast({ title: '解绑失败', icon: 'none' });
        }
      }
    }
  });
};

const goAuth = (item) => {
  const id = item?.id ?? '';
  const plate = item?.plate ? encodeURIComponent(item.plate) : '';
  uni.navigateTo({
    url: `/pages/vehicle/auth?id=${id}&plate=${plate}`
  });
};

const addVehicleBind = () => {
  uni.navigateTo({
    url: '/pages/vehicle/add'
  })
};
</script>

<style scoped>
.page {
  background-color: #fff;
  position: relative;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.box_1 {
  position: relative;
  padding: 30rpx 0;
  flex: 1;
}

.group_3 {
  background-image: url(https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/vehicle/vehicle_background.png);
  margin-top: 58rpx;
  position: relative;
  padding: 67rpx 473rpx 83rpx 46rpx;
}

.text_3 {
  color: #000;
  font-size: 58rpx;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 81rpx;
}

.box_2 {
  background-color: #fff;
  border-radius: 10px;
  height: 212rpx;
  border: 1px solid #d3d3d3;
  width: 688rpx;
  position: absolute;
  left: 31rpx;
  top: 202rpx;
  padding: 33rpx 25rpx 46rpx 29rpx;
  transition: border-color 0.3s;
}

.active-card {
  border: 1px solid #1CCCB4 !important;
}

.box_3 {
  width: 631rpx;
}

.text_4 {
  color: #000;
  font-size: 38rpx;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  text-align: left;
  white-space: nowrap;
  line-height: 54rpx;
}

.auth-btn {
  background-color: #1CCCB4;
  border-radius: 14px;
  padding: 4rpx 35rpx 6rpx 33rpx;
}

.btn-text {
  color: #fff;
  font-size: 29rpx;
  font-weight: normal;
  text-align: center;
  white-space: nowrap;
  line-height: 44rpx;
}

.box_4 {
  width: 248rpx;
  margin: 31rpx 383rpx 0 0;
}

.image-text_1 {
  display: flex;
  align-items: center;
}

.text-group {
  color: #000;
  font-size: 27rpx;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 44rpx;
  margin-left: 10rpx;
}

.divider {
  color: #7A7A7C;
  font-size: 31rpx;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 44rpx;
}

.unbind-text {
  color: #000;
  font-size: 27rpx;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 44rpx;
}

.group_4 {
  background-color: #fff;
  border-radius: 10px;
  border: 1px solid #d3d3d3;
  align-self: center;
  margin-top: 30rpx;
  width: 688rpx;
  padding: 33rpx 25rpx 46rpx 29rpx;
  transition: border-color 0.3s;
}

.first-list-card {
  margin-top: 213rpx;
}

.box_5 {
  width: 631rpx;
}

.auth-btn-done {
  background-color: rgba(28, 204, 180, 0.2);
  border-radius: 14px;
  padding: 4rpx 35rpx 6rpx 33rpx;
}

.btn-text-done {
  color: #000;
  font-size: 29rpx;
  font-weight: normal;
  text-align: center;
  white-space: nowrap;
  line-height: 44rpx;
}

.box_6 {
  width: 248rpx;
  margin: 31rpx 383rpx 0 0;
}

.footer {
  padding: 20rpx;
  width: 100%;
  position: sticky;
  bottom: 0;
  background-color: #fff;
}

.add-vehicle-btn {
  background-color: #1CCCB4;
  border-radius: 25px;
  padding: 23rpx 0;
  width: 100%;
  border: none;
}

.add-text {
  color: #fff;
  font-size: 35rpx;
  font-family: MiSans-Medium;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
  line-height: 46rpx;
}

/* 通用样式 */
page view {
  box-sizing: border-box;
  flex-shrink: 0;
}

body {
  font-family: PingFangSC-Regular, Roboto, Helvetica Neue, Helvetica, Tahoma,
    Arial, PingFang SC-Light, Microsoft YaHei;
  margin: 0;
}

button {
  margin: 0;
  padding: 0;
  border: 1px solid transparent;
  outline: none;
  background-color: transparent;
}

button:active {
  opacity: 0.6;
}

.flex-col {
  display: flex;
  flex-direction: column;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.justify-between {
  display: flex;
  justify-content: space-between;
}
</style>
